package com.duofan.gmall.seckill.scheduled;

import com.duofan.gmall.seckill.service.SeckillService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * 秒杀商品定时上架
 * 每晚3点:上架最近3天需要秒杀的商品
 * 当天 00:00:00-23:59:59
 * 明天 00:00:00-23:59:59
 * 后天 00:00:00-23:59:59
 */
@Slf4j
@Service
public class SeckillSchedule {

    @Autowired
    SeckillService seckillService;
    @Autowired
    RedissonClient redissonClient;

    private final String upload_lock = "seckill:upload:lock";

    // @Scheduled(cron = "0 0 3 * * ?")
//    @Scheduled(cron = "*/10 * * * * ?")
    public void uploadSeckillSkuLatest3Days() {
        log.info("秒杀商品上架");
        // 重复上架无需处理
        RLock lock = redissonClient.getLock(upload_lock);
        lock.lock(10, TimeUnit.SECONDS);
        try {
            seckillService.uploadSeckillSkuLatest3Days();
        } finally {
            lock.unlock();
        }
    }

}
